package ph.com.gs3.formalistics.presenter.fragements.workers;

import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.facades.UsersDataReader;
import ph.com.gs3.formalistics.model.vo.business.User;
import ph.com.gs3.formalistics.services.managers.SessionManager;
import ph.com.gs3.formalistics.services.managers.SessionManager.LoginException;
import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;

public class LoginWorkerFragment extends Fragment {

	public static final String TAG = LoginWorkerFragment.class.getSimpleName();

	private UsersDataReader userDataReader;

	private LoginWorkerFragmentListener listener;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		listener = (LoginWorkerFragmentListener) activity;
	}

	public User getActiveUser() {

		// Lazy load usersLDAO object
		if (userDataReader == null) {
			userDataReader = new UsersDataReader(getActivity());
		}

		return userDataReader.getActiveUser();

	}

	public void login(String server, String email, String password) {

		LoginTask loginTask = new LoginTask();
		loginTask.execute(server, email, password, listener);

	}

	private class LoginTask extends AsyncTask<Object, Void, User> {

		private LoginException loginException = null;
		private LoginWorkerFragmentListener listener;

		@Override
		protected User doInBackground(Object... params) {

			String server = (String) params[0];
			String email = (String) params[1];
			String password = (String) params[2];

			listener = (LoginWorkerFragmentListener) params[3];

			SessionManager sessionManager = SessionManager.getApplicationInstance();
			try {
				User authenticatedUser = sessionManager.login(server, email, password);
				return authenticatedUser;
			} catch (LoginException e) {
				loginException = e;
			}

			return null;
		}

		@Override
		protected void onPostExecute(User authenticatedUser) {
			super.onPostExecute(authenticatedUser);

			if (authenticatedUser != null) {
				listener.onLoginSuccessful(authenticatedUser);
			} else if (loginException != null && listener != null) {
				// listener.onLoginFailed(loginException.getCause().getMessage());
				if (loginException.getCause() != null) {
					FLLogger.d(TAG, loginException.getCause().getMessage());
				} else {
					FLLogger.d(TAG, loginException.getMessage());
				}

				listener.onLoginFailed(loginException.getMessage());
			}

		}

	}

	public static interface LoginWorkerFragmentListener {
		public void onLoginSuccessful(User user);

		public void onLoginFailed(String message);
	}

}
